/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:46:27
 * @LastEditTime: 2021-06-12 14:02:29
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \opdb\openplant.go
 * hnxr
 */
package opdb

import (
	"database/sql"
	"database/sql/driver"
	"errors"
	"strconv"
	"strings"
)

//driverName 驱动名
const driverName = "opsql"

func init() {
	sql.Register(driverName, &Openplant{})
}

//Openplant Openplant 数据库
type Openplant struct {
}

//Open 数据库连接字符串
//sis:openplant@172.16.125.223:8200?timeout=60
func (m *Openplant) Open(s string) (driver.Conn, error) {
	var err error
	ss := strings.Split(s, "@")
	if len(ss) != 2 {
		return nil, errors.New("connect string error")
	}

	stmp := strings.Split(ss[0], ":")
	user := strings.TrimSpace(stmp[0])
	pwd := ""
	if len(stmp) > 1 {
		pwd = strings.TrimSpace(stmp[1])
	}

	ss = strings.Split(ss[1], "?")
	stmp = strings.Split(ss[0], ":")
	host := strings.TrimSpace(stmp[0])
	port := 8200
	if len(stmp) > 1 {
		stmp[1] = strings.TrimSpace(stmp[1])
		port, err = strconv.Atoi(stmp[1])
		if err != nil {
			return nil, err
		}
	}
	timeout := 60
	eventSize := 2000
	option := 0xC00
	if len(ss) > 1 {
		stmp = strings.Split(ss[1], "&")
		for _, opt := range stmp {
			opt = strings.TrimSpace(opt)
			opt = strings.ToLower(opt)
			ss = strings.Split(opt, "=")
			if ss[0] == "timeout" {
				if len(ss) > 1 {
					timeout, err = strconv.Atoi(ss[1])
					if err != nil {
						return nil, err
					}
				}
			} else if ss[0] == "option" {
				if len(ss) > 1 {
					option, err = strconv.Atoi(ss[1])
					if err != nil {
						return nil, err
					}
				}
			} else if ss[0] == "eventSize" {
				if len(ss) > 1 {
					eventSize, err = strconv.Atoi(ss[1])
					if err != nil {
						return nil, err
					}
					if eventSize == 0 {
						eventSize = 5000
					}
				}
			}
		}
	}
	return newConn(host, port, user, pwd, timeout, option, eventSize)
	//return &Conn{host: "http://" + s + "/v1/gbase/"}, nil
}
